package com.hzlh.configuration;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Controller层监控，目前只打印日志
 */
@Slf4j
@Aspect
@Configuration
public class ControllerMonitorAspectConfiguration {

    @Value("${spring.profiles.active}")
    private String profiles;

    @Pointcut("execution(* com..*.controller..*.*(..))")
    private void monitorPoint() {

    }

    @Around("monitorPoint()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return pjp.proceed();
        }
        HttpServletRequest request= attributes.getRequest();
        Map<String, Object> map = new LinkedHashMap<>();
        long start = 0L;
        if("dev".equals(profiles)){
            MethodSignature signature = (MethodSignature) pjp.getSignature();
            String[] parameterNames = signature.getParameterNames();
            Object[] args = pjp.getArgs();
            int i = 0;
            for (Object arg : args) {
                map.put(parameterNames[i], arg);
                i++;
            }
            start = System.currentTimeMillis();
        }

        try {
            return pjp.proceed();
        } finally {
            if("dev".equals(profiles)){
                long end = System.currentTimeMillis();
                LOGGER.info("Request Address：" + request.getRequestURI() + "\n" +
                        "Method parameters：" + map + "\n" +
                        "Method execution time：" + (end - start));
            }

        }

    }

}
